/**
 * 自定义tab选型卡，没有把选项卡做了，只做了菜单的点击事件，
 * 之所以以不做选项卡，主要是觉得，， 这里可以 做灵活一些，实现方式
 * 由自己来定，大大增加灵活度。方便开发，提高开发的效率。
 */
(function($) {
	$.extend({
		tabInit:function(options){
			var defaults = {
				id:'tab-select-id',
				width:'100%',
				height:'45px',
				borderBottom:'1px solid #cccccc',
				padding:'10px 0px 0 0px',
				bgImgSelect:'../resource/images/btn11_1.png',
				bgImgNoSelect:'../resource/images/btn11_2.png',
				colorSelect:'black',
				colorNoSelect:'white',
				itemWidth:'170px',
				itemHeight:'45px',
				itemMargin:'2px 10px 0 10px',
				itemFontSize:'18px',
				itemClick:null,
				items:[]
			};
			var opts = $.extend(defaults, options);
			var $div = $("#"+opts.id);
			if($div.length == 0) {
				throw opts.id+" dom 不存在";
			}
			$div.css({
				width:opts.width,
				height:opts.height,
				padding:opts.padding,
				borderBottom:opts.borderBottom,
			});
			$.each(opts.items,function(i,item){
				var html = '';
				var marginLeft = '';
				if(i ==0) {
					marginLeft = '2px 10px 0 50px';
				}else {
					marginLeft = opts.itemMargin;
				}
				html += '<div class="item" style="cursor: pointer;color:'+opts.colorNoSelect+';margin:'+marginLeft+';line-height: '+opts.height+';height: '+opts.itemHeight+';background:url('+opts.bgImgNoSelect+') no-repeat;width: '+opts.itemWidth+';text-align: center;font-size:'+opts.itemFontSize+';font-weight: bold;float: left;">';
				html += item;
				html += '</div>';
				$div.append(html);
			});
			$div.append('<div style="clear:both;"></div>');
			$("#"+opts.id +" .item:eq(0)").css({
				color:opts.colorSelect,
				backgroundImage:'url('+opts.bgImgSelect+')'
			});
			$("#"+opts.id +" .item").on("click",function(e){
				$(this).css({
					color:opts.colorSelect,
					backgroundImage:'url('+opts.bgImgSelect+')'
				}).siblings().css({
					color:opts.colorNoSelect,
					backgroundImage:'url('+opts.bgImgNoSelect+')'
				});
				opts.itemClick($("#"+opts.id +" .item").index(this),$(this));
			});
		},
	});
	$.fn.handScroll = function(options){
		var defaults = {
			speed:1000,
			unit:20,
			initMarginTop:0,
			position:"sticky",
			animate:true,
			icon:{
				src:'',
				id:'refresh-img-id',
				width:50,
				height:50,
				position:'relative',
				zIndex:1,
				showTop:60,
				showLeft:200,
				initLeft:200,
				rotate:0,
				initRotate:0,
				speedRate:1.8,
				img:null
			}
		};
		var opts = $.extend(defaults, options);
		var $this = this;
		
		if($this.parent() == null)
			throw "没有父节点无法构建滚动窗口";
		var $parent = $this.parent();
		var $isOpen = true;
		var scrollObj = {
			pullToRefresh:function(refresh){
				opts.pullToRefresh = refresh;
			},
			pullUpLoading:function(loading) {
				opts.pullUpLoading = loading;
			},
			resize:function(){
				opts.parentHeight = $parent.height();
				opts.height = $this.height()
				opts.maxHeight = opts.height - opts.parentHeight;
				opts.marginTop = parseInt($this.css("marginTop").replace('px', ''));
				opts.marginMax = opts.marginTop - opts.maxHeight;
				opts.isPullLoading = opts.maxHeight > 0 ? true : false;
				opts.$bottom_marginTop = -(opts.height - opts.parentHeight - opts.initMarginTop);
			},
			refresh:function(){
				scrollObj.resize();
				if(opts.animate) {
					opts.icon.img.animate({top:opts.icon.initTop},opts.speed,function(){
						util.closeAutoRotate();
						$isOpen = true;
					});
				}
			},
			loading:function(){
				scrollObj.resize();
			},
			pullRefreshProgress:function(){
				
			},
			refreshIcon:function(){
				if( opts.icon.img == null)
					$parent.prepend('<img id="'+opts.icon.id+'" style="transform:rotate('+opts.icon.initRotate+'deg);-ms-transform:rotate('+opts.icon.initRotate+'deg);-moz-transform:rotate('+opts.icon.initRotate+'deg);-webkit-transform:rotate('+opts.icon.initRotate+'deg);-o-transform:rotate('+opts.icon.initRotate+'deg);"/>')
				opts.icon.img = $("#"+opts.icon.id);
				opts.icon.img.attr('src',opts.icon.src);
				opts.icon.initTop = -(opts.icon.width-opts.initMarginTop);
				opts.icon.img.css({
					width:opts.icon.width+"px",
					height:opts.icon.height+"px",
					position:opts.icon.position,
					zIndex:opts.icon.zIndex,
					left:opts.icon.initLeft+"px",
					top:opts.icon.initTop+"px"
				});
			}
		}
		opts.initMarginTop = parseInt($this.css("marginTop").replace('px', ''));
		if(opts.animate) {
			opts.initMarginTop = -opts.icon.width
			$this.css({"position":opts.position,"marginTop":opts.initMarginTop+"px"});
			scrollObj.refreshIcon();
		}else {
			$this.css({"position":opts.position});
			
		}
		var util = {
			autoRotate:function(ar){
				if(ar) {
					var val = (Math.abs(ar.curValue)+Math.abs(ar.value))/ar.time;
					val = val<1?opts.icon.speedRate:val;
					var clearTerval = setInterval(function(){
						ar.curValue = ar.curValue - val;
						opts.icon.img.css({transform:'rotate('+ar.curValue+'deg)'});
						if(ar.curValue < ar.value) {
							window.clearInterval(clearTerval);
							opts.icon.rotate = ar.curValue;
							util.autoRotate();
						}
					},1);
				}else {
					opts.icon.clearRefresh = setInterval(function(){
						opts.icon.rotate = opts.icon.rotate - opts.icon.speedRate;
						opts.icon.img.css({transform:'rotate('+opts.icon.rotate+'deg)'});
					},1);
				}
				
			},
			closeAutoRotate:function(){
				debugger;
				window.clearInterval(opts.icon.clearRefresh);
				opts.icon.rotate = opts.icon.initRotate;
				//opts.icon.img.css({transform:'rotate('+opts.icon.initRotate+'deg)'});
			},
			
		}
		
		
		scrollObj.resize();
		var $mouseFlag = true;
		// 这个是鼠标滚轮滚动
		$this.on("mousewheel DOMMouseScroll", function (e) {
	        var delta = (e.originalEvent.wheelDelta && (e.originalEvent.wheelDelta > 0 ? 1 : -1)) ||  // chrome & ie
	                (e.originalEvent.detail && (e.originalEvent.detail > 0 ? -1 : 1));              // firefox
	        if (delta > 0) {
				var th = parseInt($this.css("marginTop").replace('px', '')) + opts.unit;
				if (th < opts.marginTop) {
					$this.css("marginTop",th);
					
					$mouseFlag = true;
				}else if($mouseFlag){ // 这个是向下滚动
					$mouseFlag = false;
				}
	        } else if (delta < 0) {
	        	var th = parseInt($this.css("marginTop").replace('px', '')) - opts.unit;
	    		if(th > opts.marginMax ) {
	    			$this.css("marginTop",th);
	    			$mouseFlag = true;
				}else if($mouseFlag){ // 这个是向上滚动
					$mouseFlag = false;
				}
	        }
	    });
		// 来这个是鼠标拖动事件哦
		var startY=0,$flagAnmate=false;
		$this.mousedown(function(e){
			startY = e.pageY;
			
			$this.mousemove(function(mme){
				console.log($isOpen);
				if(!$isOpen)
					return;
				opts.$marginTop = parseInt($this.css("marginTop").replace('px', ''));
				var distanceY = mme.pageY - startY;
				var marginTop = opts.$marginTop + distanceY;
				if(startY < mme.pageY  ) {
					$flagAnmate = true; 
					if(opts.$marginTop < opts.parentHeight ) { // 这个是下拉刷新
						$this.css("marginTop",marginTop);
						if(opts.animate) {
							var curImgTop = parseInt(opts.icon.img.css("top").replace('px', ''));
							opts.icon.rotate += distanceY*opts.icon.speedRate;
							opts.icon.img.css({
								top:curImgTop+distanceY,
								transform:'rotate('+opts.icon.rotate+'deg)'
							});
						}
					}
				}else {
					if(!opts.isPullLoading)
						return ;
					$flagAnmate = true;
					var temp = opts.$bottom_marginTop - opts.parentHeight;
					if(Math.abs(temp) > Math.abs(opts.$marginTop) ) { // 这个是上拉加载
						$this.css("marginTop",marginTop);
					}
				}
				startY = mme.pageY;
			});
			$(document).mouseup(function(){
				$this.off('mousemove');
				
				if(opts.$marginTop > opts.initMarginTop && $flagAnmate ) { //下拉刷新
					$flagAnmate = false;
					
					$this.animate({marginTop:opts.initMarginTop},opts.speed,function(){
						console.log('下拉刷新动画完成');
						startY = 0;
						if(opts.pullToRefresh != null && typeof opts.pullToRefresh === 'function'){
							opts.pullToRefresh();
						}
					});
					// 刷新动画效果
					if(opts.animate) {
						debugger;
						$isOpen = false;
						opts.icon.img.animate({top:opts.icon.showTop},opts.speed,function(){});
						util.autoRotate({
							time:opts.speed,
							value:opts.icon.initRotate,
							curValue:opts.icon.rotate
						});
					}
					// 1. 这里应该判断是有问题的  。。。 我要 当前 的margin  
				}else if(opts.$bottom_marginTop > opts.$marginTop && $flagAnmate ) { //上拉加载
					$flagAnmate = false;
					$this.animate({marginTop:opts.$bottom_marginTop-40},opts.speed,function(){
						console.log('上拉加载动画完成');
						startY = 0;
						if(opts.pullUpLoading != null && typeof opts.pullUpLoading === 'function'){
							opts.pullUpLoading();
						}
					});
				}
			});
		});
		return scrollObj;
	}
})(jQuery)
